﻿using Microsoft.VisualStudio.Text;

namespace VSAdditionalCommands
{
    [Command(PackageIds.WrapQuotesCommand)]
    internal sealed class WrapQuotesCommand : BaseCommand<WrapQuotesCommand>
    {
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            await Package.JoinableTaskFactory.SwitchToMainThreadAsync();
            DocumentView docView = await VS.Documents.GetActiveDocumentViewAsync();
            if (docView?.TextView == null) return;
            SnapshotPoint position = docView.TextView.Caret.Position.BufferPosition;

            if (docView.TextBuffer != null)
            {
                var snapshot = docView.TextBuffer.CurrentSnapshot;
                var text = snapshot.GetText(new Span(position.Position, snapshot.Length - position.Position));
                var spaceRegex = new System.Text.RegularExpressions.Regex(@"[^A-Za-z0-9а-яА-ЯеЁ]+?");
                var spaceRegexBack = new System.Text.RegularExpressions.Regex(@"[^A-Za-z0-9а-яА-ЯеЁ]+?", System.Text.RegularExpressions.RegexOptions.RightToLeft);
                var spaceNextPosition = spaceRegex.Match(text);
                if (spaceNextPosition.Success)
                {
                    docView.TextBuffer?.Insert(position.Position + spaceNextPosition.Index, "\"");
                    text = snapshot.GetText(new Span(0, position.Position+1));
                    var spacePrevPosition = spaceRegexBack.Match(text);
                    if (spacePrevPosition.Success)
                    {
                        docView.TextBuffer?.Insert(spacePrevPosition.Index + 1, "\"");
                    }
                }
            }
        }
    }
}
